package com.antstorm.statistics.service.mqtt;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * mqtt消息处理核心
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
public class MqttMsgHandlerCore {

    @Autowired
    private ApplicationContext applicationContext;

    private static Map<String, MqttMsgHandlerAbs> handleCore=new HashMap<>();

    /**
     * 根据topic获取消息处理器
     *
     * @param topic
     * @return
     */
    public MqttMsgHandler getHandler(String topic) {
        return handleCore.get(topic);
    }


    @PostConstruct
    private void initCore(){
        Map<String, MqttMsgHandlerAbs> allHandler  =applicationContext.getBeansOfType(MqttMsgHandlerAbs.class);
        allHandler.entrySet()
                .stream()
                .forEach(e->{
                    handleCore.put(e.getValue().topic, e.getValue());
                });
    }

}
